<?php namespace App\Models;
/**
 * Created by PhpStorm.
 * User: 都大爽
 * Date: 2016/11/30
 * Time: 13:53
 */
require '../vendor/autoload.php';
include_once '../aliyun-php-sdk-core/Config.php';

use OSS\OssClient;
use DefaultAcsClient;
use DefaultProfile;

use Mts\Request\V20140618 as Mts;

class ChangeVideos
{
    public $mts_region;
    public $oss_region;
    public $mts_endpoint;
    public $oss_endpoint;

    public $access_key_id;
    public $access_key_secret;
    public $pipeline_id;
    public $transcode_template_id;
    public $watermark_template_id;
    public $input_bucket;
    public $output_bucket;
    public $profile;
    public $client;

    public function __construct()
    {
        $this->mts_region = 'cn-shanghai';
        $this->oss_region = 'oss-cn-shanghai';
        $this->mts_endpoint = 'http://mts.cn-shanghai.aliyuncs.com';
        $this->oss_endpoint = env('ALIYUN_OSS_ENDPOINT','oss-cn-shanghai.aliyuncs.com');
        $this->access_key_id = env('ALIYUN_OSS_ACCESS_ID');
        $this->access_key_secret = env('ALIYUN_OSS_ACCESS_KEY');
        $this->transcode_template_id = '';
        $this->pipeline_id = '3500393f3f5b4a9c99ee078d550eed90';
        $this->watermark_template_id = '';
        $this->input_bucket = env('ALIYUN_OSS_BUCKET', 'example-bucket');
        $this->output_bucket = env('ALIYUN_OSS_BUCKET', 'example-bucket');
        $this->profile = DefaultProfile::getProfile($this->mts_region, $this->access_key_id, $this->access_key_secret);
        $this->client = new DefaultAcsClient($this->profile);

    }

    public function uploadFile($filename, $bucket, $obj)
    {
        $ossClient = new OssClient($this->access_key_id,
            $this->access_key_secret,
            $this->oss_endpoint,
            false);
        $ossClient->uploadFile($bucket, $obj, $filename);

        return array(
            'Location' => $this->oss_region,
            'Bucket' => $bucket,
            'Object' => urlencode($obj)
        );
    }

    public function snapshotJobFlow($input_file)
    {
        $snapshot_job = $this->submitSnapshotJob($input_file);

        print 'Snapshot success, the target file url is http://' .
            $snapshot_job->{'SnapshotConfig'}->{'OutputFile'}->{'Bucket'} . '.' .
            $snapshot_job->{'SnapshotConfig'}->{'OutputFile'}->{'Location'} . '.aliyuncs.com/' .
            urldecode($snapshot_job->{'SnapshotConfig'}->{'OutputFile'}->{'Object'}) . "\n";
    }

    public function submitSnapshotJob($input_file)
    {
        $obj = 'demo/snapshots/' . uniqid() . '-中文.jpg';
        $snapshot_output = array(
            'Location' => $this->oss_region,
            'Bucket' => $this->input_bucket,
            'Object' => urlencode($obj)
        );
        $snapshot_config = array(
            'OutputFile' => $snapshot_output,
            'Time' => 1000
        );

        $request = new Mts\SubmitSnapshotJobRequest();
        $request->setAcceptFormat('JSON');
        $request->setInput(json_encode($input_file));
        $request->setSnapshotConfig(json_encode($snapshot_config));

        $response = $this->client->getAcsResponse($request);
        return $response->{'SnapshotJob'};
    }

    public function transcodeJobFlow($input_file, $watermark_file)
    {
        $this->systemTemplateJobFlow($input_file, $watermark_file);

        $this->userCustomTemplateJobFlow($input_file, $watermark_file);
    }

    public function systemTemplateJobFlow($input_file, $watermark_file)
    {
        $analysis_id = $this->submitAnalysisJob($input_file, $this->pipeline_id);
        $analysis_job = $this->waitAnalysisJobComplete($analysis_id);
        $template_ids = $this->getSupportTemplateIds($analysis_job);

        # 可能会有多个系统模板，这里采用推荐的第一个系统模板进行转码
        $transcode_job_id = $this->submitTranscodeJob($input_file, $watermark_file, $template_ids[0]);
        $transcode_job = $this->waitTranscodeJobComplete($transcode_job_id);

        print 'Transcode success, the target file url is http://' .
            $transcode_job->{'Output'}->{'OutputFile'}->{'Bucket'} . '.' .
            $transcode_job->{'Output'}->{'OutputFile'}->{'Location'} . '.aliyuncs.com/' .
            urldecode($transcode_job->{'Output'}->{'OutputFile'}->{'Object'}) . "\n";
    }

    public function submitAnalysisJob($input_file)
    {
        $request = new Mts\SubmitAnalysisJobRequest();
        $request->setAcceptFormat('JSON');
        $inputFile = [
            'Bucket' => $this->input_bucket,
            'Location' => $this->oss_region,
            'Object' => $input_file
        ];
        $request->setInput(json_encode($inputFile));
        $request->setPriority(5);
        $request->setUserData('SubmitAnalysisJob userData');
        $request->setPipelineId($this->pipeline_id);
        //var_dump($this->pipeline_id);exit();
        $response = $this->client->getAcsResponse($request);
        //var_dump($response);exit();
        return $response->{'AnalysisJob'}->{'Id'};
    }

    public function waitAnalysisJobComplete($analysis_id)
    {
        while (true)
        {
            $request = new Mts\QueryAnalysisJobListRequest();
            $request->setAcceptFormat('JSON');
            $request->setAnalysisJobIds($analysis_id);

            $response = $this->client->getAcsResponse($request);
            $state = $response->{'AnalysisJobList'}->{'AnalysisJob'}[0]->{'State'};
            if ($state != 'Success')
            {
                if ($state == 'Submitted' or $state == 'Analyzing')
                {
                    sleep(5);
                } elseif ($state == 'Fail') {
                    print 'AnalysisJob is failed!';
                    return null;
                }
            } else {
                return $response->{'AnalysisJobList'}->{'AnalysisJob'}[0];
            }
        }
        return null;
    }

    public function getSupportTemplateIds($analysis_job)
    {
        $result = array();

        foreach ($analysis_job->{'TemplateList'}->{'Template'} as $template)
        {
            $result[] = $template->{'Id'};
        }

        return $result;
    }

    public function submitTranscodeJob($input_file, $template_id)
    {
        $watermark_config = array();
     //   $watermark_config[] = array(
     //       'InputFile' => json_encode($watermark_file),
     //       'WaterMarkTemplateId' => $this->watermark_template_id
     //   );

        $inputFile = [
            'Bucket' => $this->input_bucket,
            'Location' => $this->oss_region,
            'Object' => $input_file
        ];

        $obj = 'works/uploads/aa.flv';
        $outputs = array();
        $outputs[] = array(
            'OutputObject'=> urlencode($obj),
            'TemplateId' => $template_id,
       //     'WaterMarks' => $watermark_config
        );

        $request = new Mts\SubmitJobsRequest();
        $request->setAcceptFormat('JSON');
        $request->setInput(json_encode($inputFile));
        $request->setOutputBucket($this->output_bucket);
        $request->setOutputLocation($this->oss_region);
        $request->setOUtputs(json_encode($outputs));
        $request->setPipelineId($this->pipeline_id);

        $response = $this->client->getAcsResponse($request);
        return $response->{'JobResultList'}->{'JobResult'}[0]->{'Job'}->{'JobId'};
    }

    public function waitTranscodeJobComplete($transcode_job_id)
    {
        while (true)
        {
            $request = new Mts\QueryJobListRequest();
            $request->setAcceptFormat('JSON');
            $request->setJobIds($transcode_job_id);

            $response = $this->client->getAcsResponse($request);
            $state = $response->{'JobList'}->{'Job'}[0]->{'State'};
            if ($state != 'TranscodeSuccess')
            {
                if ($state == 'Submitted' or $state == 'Transcoding')
                {
                    sleep(5);
                } elseif ($state == 'TranscodeFail') {
                    print 'Transcode is failed!';
                    return null;
                }
            } else {
                return $response->{'JobList'}->{'Job'}[0];
            }
        }
        return null;
    }

    public function userCustomTemplateJobFlow($input_file, $watermark_file)
    {
        $transcode_job_id = $this->submitTranscodeJob($input_file, $watermark_file, $this->transcode_template_id);
        $transcode_job = $this->waitTranscodeJobComplete($transcode_job_id);

        print 'Transcode success, the target file url is http://' .
            $transcode_job->{'Output'}->{'OutputFile'}->{'Bucket'} . '.' .
            $transcode_job->{'Output'}->{'OutputFile'}->{'Location'} . '.aliyuncs.com/' .
            urldecode($transcode_job->{'Output'}->{'OutputFile'}->{'Object'}) . "\n";
    }


}